




//
//  ZOrderSubViewController.m
//  ZQLearn
//
//  Created by macfeel on 2019/4/21.
//  Copyright © 2019 macfeel. All rights reserved.
//

#import "ZOrderSubViewController.h"
#import "OrderModel.h"
#import "OrderCell.h"
#import "OrderSectionFooterView.h"
#import "ZPayViewController.h"
@interface ZOrderSubViewController ()<UITableViewDelegate,UITableViewDataSource>

@property(nonatomic,strong)UITableView *tableView;
@property (nonatomic,strong)NSMutableArray *dataArray;
@property (nonatomic,assign)NSInteger index;
@property (nonatomic,assign)NSInteger currentPage;

@property (nonatomic,assign)NSInteger sectionIndex;
///订单状态
@property (nonatomic,assign)NSInteger orderStatus;

@property (nonatomic,strong)OrderSectionFooterView *footer;
@property (nonatomic,copy)NSString *cid;

@end
#define cellIdentifier @"order"

@implementation ZOrderSubViewController
-(UITableView *)tableView{
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0 , 3, ScreenWidth , ScreenHeight - kTabHeight-ScreenHeightFlex) style:UITableViewStyleGrouped];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.rowHeight = 95.f;
        _tableView.backgroundColor = kBackgroundColor;
        [_tableView registerNib:[UINib nibWithNibName:@"OrderCell" bundle:nil] forCellReuseIdentifier:cellIdentifier];
                WeakStament(ws);
                _tableView.mj_header = [CustomRefreshHeader headerWithRefreshingBlock:^{
                    [ws refreshData];
                }];
        
//        _tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
//            [ws loadMoreData];
//        }];
        _tableView.showsVerticalScrollIndicator = NO;
        _tableView.tableFooterView = [UIView new];

    }
    return _tableView;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.index = -1;
    self.currentPage = 1;
    self.sectionIndex = 0;
    self.orderStatus = 0;
    self.dataArray = [NSMutableArray array];
    [self.view addSubview:self.tableView];
//    self.view.backgroundColor = kLightGrayColor;
//     [self showNoDataImageView:@"none" withTitle:@"暂无数据哦"];
    // Do any additional setup after loading the view.
}

#pragma mark - datasource
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return self.dataArray.count;
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
//    return self.dataArray.count;
    OrderModel *model = self.dataArray[section];
    return model.orderCommodityInfoResponDTOList.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    OrderModel *model = self.dataArray[indexPath.section];
    OrderModel *subModel = model.orderCommodityInfoResponDTOList[indexPath.row];
    OrderCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier forIndexPath:indexPath];
    cell.nameLab.text = subModel.commodityInfo[@"name"];
    cell.jifenLab.text = [NSString stringWithFormat:@"%@积分",subModel.commodityInfo[@"integral"]];
    cell.numLab.text =[NSString stringWithFormat:@"X%@",subModel.commodityNumber];
    [cell.headImg sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",kStorePicServerUrl,subModel.commodityInfo[@"photo"]]] placeholderImage:nil];
    return cell;
//    return nil;
}


#pragma mark - section head
#define OrderSectionHeaderHeight 10
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    
    return OrderSectionHeaderHeight;
    //如果设置section的header高度，不设置footer高度，footer默认等于header高度
}


- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, OrderSectionHeaderHeight)];
    view.backgroundColor = kBackgroundColor;
    return view;
}

#pragma mark - section foot
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 192;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    
    OrderModel *model = self.dataArray[section];
    self.cid = model.ID;
    YYLog(@"%@**%@",self.cid,model.ID);
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, 192)];
    view.backgroundColor = kBackgroundColor;
    OrderSectionFooterView *foo = [[[NSBundle mainBundle]loadNibNamed:@"OrderSectionFooterView" owner:self options:nil]lastObject];
    foo.frame = CGRectMake(0, 0, ScreenWidth, 192);
    [view addSubview:foo];
    ///orderStatus   1.待支付 2.待发货，3.待收货，4.已完成
    if (model.orderStatus==1) {
        ///待支付
        self.orderStatus = 1;
        [foo.confirmBtn setTitle:@"去付款" forState:UIControlStateNormal];
#pragma mark - 待支付暂时屏蔽 业务逻辑处理好后可以把下面代码屏蔽
        foo.confirmBtn.hidden = YES;
        
    }else if (model.orderStatus==3){
        self.orderStatus = 3;
        [foo.confirmBtn setTitle:@"确认收货" forState:UIControlStateNormal];
        
    }else{
        ///待发货和已完成没有按钮
        foo.confirmBtn.hidden = YES;
    }

    ///公共部分
    [foo.confirmBtn addTarget:self action:@selector(confirmAction:) forControlEvents:UIControlEventTouchUpInside];
    foo.confirmBtn.tag = section;
    YYLog(@"%ld",section);
    
    ////配置foot收货信息
    foo.commodityNumLab.text = [NSString stringWithFormat:@"共%@件商品,总付款:",model.commodityNumber];
    foo.priceLab.text = [NSString stringWithFormat:@"%@元+%@积分",model.money,model.consumeIntegral];
    foo.orderNumberLab.text = [NSString stringWithFormat:@"订单号: %@",model.orderNumber];
    foo.receiverLab.text =[NSString stringWithFormat:@"收货人: %@   %@",model.userAddressInfo[@"name"],model.userAddressInfo[@"phone"]];
    NSString *address = [NSString stringWithFormat:@"收货地址: %@%@%@%@",model.userAddressInfo[@"province"],model.userAddressInfo[@"city"],model.userAddressInfo[@"area"],model.userAddressInfo[@"address"]];
    foo.receiveAddLab.text = address;
    foo.timeLab.text = model.orderTime;
    return view;
}

- (void)confirmAction:(UIButton *)btn{
    
    ///*****************************************************
    ////这种传递索引的方法   有点意思  很有创意的一个方法  yeah!!!
    OrderModel *model = self.dataArray[btn.tag];
    YYLog(@"%@**%@",model.ID,model.commodityNumber);
    if (self.orderStatus==3) {
        //待收货
        ///确认收货   4
        NSDictionary *dic = @{@"id":model.ID,@"orderStatus":@"4",};
        [ZNetworkService postRequestWithBaseUrl:kConfirmReceiveUrl setParameters:dic success:^(id result) {
            YYLog(@"%@",result);
            if ([result[@"errorCode"]integerValue]==0) {
                [AFToast showText:@"收货成功"];
                ///收货成功后这调信息就进入了已完成的列表
                [self.tableView reloadData];
            }else{
                [AFToast showText:result[@"errorMsg"]];
            }
        } fail:^(NSError *error) {
            
        } delegater:nil];
        
    }else{
        
#pragma mark - 去付款
        
        ///去付款
        ZPayViewController *pay = [ZPayViewController new];
        
        ///这个是orderModel
        pay.model = model;
        
        [self.navigationController pushViewController:pay animated:YES];
        
    }
    
}


#pragma mark ZJScrollPageViewChildVcDelegate
- (void)zj_viewWillAppearForIndex:(NSInteger)index{
    YYLog(@"%ld",index);
    self.index = index;
    //    [UserModel shareInstance].tabIndex = index;
    //    self.currentIndexId = index;
}
- (void)zj_viewDidAppearForIndex:(NSInteger)index{
    
}
- (void)zj_viewWillDisappearForIndex:(NSInteger)index{
    
}
- (void)zj_viewDidDisappearForIndex:(NSInteger)index{
    
}
- (void)zj_viewDidLoadForIndex:(NSInteger)index{
    //这里具体处理请求逻辑不同的页面根据索引进行请求
    YYLog(@"%ld",index);
    //    self.currentIndex = index;
    //    [self loadDataWithIndex:index];
    //    [self loadDataWithIndex:[UserModel shareInstance].tabIndex];
    [self loadDataWithIndex:index];
}


-(void)loadDataWithIndex:(NSInteger)index{

    NSString *orderStatus;
    if (index==0) {
        //全部订单
        orderStatus = @"";
        
    }else if (index==1){
        //待付款
        orderStatus = @"1";
        
    }else if (index==2){
        //待发货
        orderStatus = @"2";
    }else if(index==3){
        //待收货
        orderStatus = @"3";
    }else{
        //已完成
        orderStatus = @"4";
    }
    
    NSString *userid = [[NSUserDefaults standardUserDefaults]objectForKey:kUserId];
    YYLog(@"%@",userid);
    //    if (index==0) {
    ///一定要弄清赋值和等于的不同，index==0  注意
    ///orderStatus  1.待支付 2.待发 货 ，3.待收货，4.
    NSDictionary *dic = @{@"pageIndex":@(self.currentPage),@"pageSize":@"100",@"userInfo.id":userid,@"orderStatus":orderStatus,@"finance":@"0",};
    //    }
    
    if (self.currentPage==1) {
        [self.dataArray removeAllObjects];
    }
    [ZNetworkService postRequestWithBaseUrl:kOrderListUrl setParameters:dic success:^(id result){
        WeakStament(ws);
        YYLog(@"%@",result);
        ///双重遍历
        if ([result[@"errorCode"]integerValue]==0) {
            NSArray *arr = result[@"result"];
            for (NSDictionary *dic in arr) {
                OrderModel *model = [OrderModel mj_objectWithKeyValues:dic];
                NSMutableArray *tempArray = [NSMutableArray array];
                for (NSDictionary *subDic in model.orderCommodityInfoResponDTOList) {
                    OrderModel *subModel = [OrderModel mj_objectWithKeyValues:subDic];
                    YYLog(@"%@**图片:%@",subModel.commodityInfo[@"integral"],subModel.commodityInfo[@"photo"]);
                    [tempArray addObject:subModel];
                }
                model.orderCommodityInfoResponDTOList = [tempArray copy];
                YYLog(@"%@",model.orderNumber);
                [ws.dataArray addObject:model];
                [ws.tableView reloadData];
                [ws endRefresh];
                ///空判断放的位置
                if (arr.count==0) {
                    [ws noMoreData];
                }
            }
        }else{
            [AFToast showText:result[@"errorMsg"]];
            [AFToast showText:@"后台返回数据异常"];
            [self endRefresh];
        }
    } fail:^(NSError *error) {
        [self endRefresh];
    } delegater:nil];
}

- (void)refreshData{

    self.currentPage = 1;
    [self loadDataWithIndex:self.index];
}

- (void)endRefresh{
    [self.tableView.mj_header endRefreshing];
    [self.tableView.mj_footer endRefreshing];
}


- (void)loadMoreData{
    self.currentPage++;
    [self loadDataWithIndex:self.index];
}


///没有更多数据
- (void)noMoreData {
    [self.tableView reloadData];
    [self.tableView.mj_footer endRefreshingWithNoMoreData];
}



@end
